package com.hschinese.pronunciation.widget;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.bean.AppDataBean;
import com.hschinese.pronunciation.bean.AppResourceMap;
import com.hschinese.pronunciation.bean.TestChinesePraciticeBean;
import com.hschinese.pronunciation.db.DBHelper;
import com.hschinese.pronunciation.interfaces.LessonProgressInterface;
import com.hschinese.pronunciation.interfaces.NextLessonInterface;
import com.hschinese.pronunciation.interfaces.PlayCompleteListener;
import com.hschinese.pronunciation.interfaces.RecordStatusListener;
import com.hschinese.pronunciation.interfaces.VolumeListener;
import com.hschinese.pronunciation.utils.AnimatorUtil;
import com.hschinese.pronunciation.utils.DensityUtil;
import com.hschinese.pronunciation.utils.HsSoundUtil;
import com.hschinese.pronunciation.utils.Logger;
import com.hschinese.pronunciation.utils.ScreenUtil;
import com.hschinese.pronunciation.utils.SimpleRecordUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import studychinese.activity.ChinaReportActivity;
import studychinese.callback.DialogCallback;
import studychinese.config.AppUrl;
import studychinese.config.Url;
import studychinese.model.UserBean;
import studychinese.utils.ToastUtils;

import static com.hschinese.pronunciation.R.id.edit_view;
import static com.hschinese.pronunciation.R.id.ll_up;
import static com.hschinese.pronunciation.R.id.tv_hao;
import static com.hschinese.pronunciation.R.id.tv_hao1;
import static com.hschinese.pronunciation.R.id.tv_hao2;


/**
 * Created by wo on 2015/11/5.
 */
public class StudyChinapracticeView extends LinearLayout {


    @Bind(tv_hao)
    TextView tvHao;
    @Bind(edit_view)
    EditView editView;
    @Bind(tv_hao1)
    TextView tvHao1;
    @Bind(R.id.tv_keyboardtishi)
    TextView tv_keyboardtishi;
    @Bind(tv_hao2)
    TextView tvHao2;
    @Bind(ll_up)
    RelativeLayout llUp;
    @Bind(R.id.ll_guan)
    LinearLayout ll_guan;
    @Bind(R.id.keyboard_view)
    SKeyboardView keyboardView;
    @Bind(R.id.ll_keyboard)
    LinearLayout llKeyboard;
    @Bind(R.id.ll_priactictice_contain)
    LinearLayout ll_priactictice_contain;
    @Bind(R.id.rlContstrctionParient)
    RelativeLayout rlContstrctionParient;
    @Bind(R.id.single_syllable_play_control)
    PlayControlView singleSyllablePlayControl;
    private Activity mContext = null;
    private int height = 0;
    private View mView = null;
    private View mViewcontent = null;
    private Cursor cursor;
    private ViewGroup anim_mask_layout;//动画层
    private int lessonType = 0;
    private int weithLess = 0;
    private int currentPosition = 0;
    private List<AppDataBean> mDataList;
    private List<Integer> picLists;


    Set setDown = new HashSet();
    private LessonProgressInterface mListener = null;
    private NextLessonInterface mNextListener = null;
    private String mMp3SourceDir = null;
    private boolean isFirst = true;
    private int bg1Id, bg2id;
    private AlphaAnimation alphaAnimation1;
    private TranslateAnimation alphaAnimation2;
    private List<TextView> textViews;
    private List<TestChinesePraciticeBean.DataBean> mResultdataList;
    private TestChinesePraciticeBean chinesePraciceInfor;
    private String isFristSelete="";
    private List<String> wrongList;

    public StudyChinapracticeView(Context context) {
        super(context);
        initViews(context);
    }
    public void setVolumeListener(VolumeListener l) { singleSyllablePlayControl.setVolumeListener(l); }

    public void setRecordListener(RecordStatusListener l) { singleSyllablePlayControl.setRecordListener(l); }
    public StudyChinapracticeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initViews(context);
    }

    private void initViews(Context context) {
        mContext = (Activity) context;
        mView = LayoutInflater.from(context).inflate(R.layout.study_chinapracitce_view, null);

        ButterKnife.bind(this, mView);
        this.addView(mView);
    }

    public void setCurrentPosition(int pos) {
        currentPosition = pos;
    }

    public void initData() {
        mDataList = new ArrayList<AppDataBean>();
        wrongList = new ArrayList<>();
        chinesePraciceInfor = UserBean.getChinesePraciceInfor();
        mResultdataList = chinesePraciceInfor.getData();
        mResultdataList.clear();
        cursor = DBHelper.getInstance(mContext).query(DBHelper.RES_TABLE, " type=? ", new String[]{lessonType + ""});
        if (cursor != null)
            Logger.e("xionghy-cursor: " + cursor.getCount());
        while (cursor.moveToNext()) {
            AppDataBean d = new AppDataBean();
            d.setChinese(cursor.getString(cursor.getColumnIndex("chinese")));
            d.setPinyin(cursor.getString(cursor.getColumnIndex("pinyin")));
            d.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
            d.setTone(cursor.getString(cursor.getColumnIndex("tone")));
            d.setAudioName(cursor.getString(cursor.getColumnIndex("audioName")));
            d.setPicName(cursor.getString(cursor.getColumnIndex("picName")));
            d.setType(cursor.getInt(cursor.getColumnIndex("type")));
            d.setGroupID(cursor.getInt(cursor.getColumnIndex("groupId")));
            d.setWeight(cursor.getInt(cursor.getColumnIndex("weight")));
            mDataList.add(d);
            TestChinesePraciticeBean.DataBean dataBean = new TestChinesePraciticeBean.DataBean();
            dataBean.setDoing(false);
            mResultdataList.add(dataBean);
        }
        if (mDataList.size() <= 0) {
            Logger.e("获取到的数据为空。。。。");
            return;
        }
        Logger.e("xionghy - " + mDataList.size());
        Logger.e("xionghy: " + mDataList.get(currentPosition).toString());
        updateViewData();
    }

    private void updateViewData() {
        if (mListener != null) {
            mListener.setProgress(mDataList.size(), currentPosition);
        }
        AppDataBean data = mDataList.get(currentPosition);
         isFristSelete="";
        TestChinesePraciticeBean.DataBean dataBean = mResultdataList.get(currentPosition);

        mMp3SourceDir = AppResourceMap.getMp3Fold(lessonType) + data.getAudioName().replace("|", "") + ".mp3";
        singleSyllablePlayControl.setStandardUrl(mMp3SourceDir);
        singleSyllablePlayControl.playStandard();
        ll_priactictice_contain.removeAllViews();
        editView.getText().clear();
        singleSyllablePlayControl.setRecordVisibility(View.GONE);
        singleSyllablePlayControl.setPlayRecordVisibility(View.GONE);
        int weight = data.getWeight();
        String[] splitHanzi = data.getChinese().replace("|", " ").split(" ");
        String[] splitPinYIN = data.getPinyin().replace("|", " ").split(" ");
        String[] splitDaZi = data.getPicName().replace("|", " ").split(" ");
        String[] splitPhone = data.getPhone().replace("|", " ").split(" ");
          if(splitDaZi.length==3){
              tvHao.setText(splitDaZi[0]);
              tvHao1.setText(splitDaZi[1]);
              tvHao2.setText(splitDaZi[2]);
          }
        textViews = new ArrayList<>();
        textViews.clear();
        for (int i = 0; i < splitHanzi.length; i++) {
            mViewcontent = LayoutInflater.from(mContext).inflate(R.layout.view_chinapractice, null);
            TextView tv_chinapricatice_pinyin = (TextView) mViewcontent.findViewById(R.id.tv_chinapricatice_pinyin);
            TextView tv_chinapricatice_hanzi = (TextView) mViewcontent.findViewById(R.id.tv_chinapricaticehanzi);
            if (i == weight) {

                if(dataBean.isDoing()){
                    tv_chinapricatice_hanzi.setText(splitHanzi[i]);
                    textViews.add(tv_chinapricatice_hanzi);
                }else {
                    tv_chinapricatice_pinyin.setText(splitPinYIN[i]);
                    tv_chinapricatice_hanzi.setText("");
                    tv_chinapricatice_hanzi.setTextSize(26);
                    tv_chinapricatice_hanzi.setText(splitPhone[i]);
                    tv_chinapricatice_hanzi.setTextColor(getResources().getColor(R.color.gray_light));
                    textViews.add(tv_chinapricatice_hanzi);

                }

            } else {
                tv_chinapricatice_pinyin.setVisibility(INVISIBLE);
                tv_chinapricatice_hanzi.setBackgroundColor(getResources().getColor(R.color.transparent));
                tv_chinapricatice_hanzi.setText(splitHanzi[i]);
            }
            ll_priactictice_contain.addView(mViewcontent);
        }

        addAnimation();
        keyboardViewReset();
        keyboardView.setCurrentKeyboard(1);
        setSubView();
        initEvent();
        setEditListener(splitPhone[weight]);

    }

    private void setEditListener(final String str) {
        editView.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    if(textViews.size()>0){
                        textViews.get(0).setText("");
                        textViews.get(0).setTextSize(26);
                    }
                    editView.getText().clear();
                } else {
                    // 此处为失去焦点时的处理内容
                }
            }
        });
        editView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                tv_keyboardtishi.setText(editView.getText().toString());

                if(textViews.size()>=1){
                      textViews.get(0).setText(editView.getText().toString());
                    textViews.get(0).setTextColor(getResources().getColor(R.color.white));
                }

                if (editView.getText().toString().equals(str)) {
                    llUp.setVisibility(View.VISIBLE);

                } else {
                    llUp.setVisibility(View.GONE);
                }


            }
        });
    }

    /**
     * /**
     * 关闭软键盘
     */
    public void closeKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public void setLessonType(int type) {
        lessonType = type;

    }

    private void initEvent() {
        editView.setOnKeyboardListener(new EditView.OnKeyboardListener() {
            @Override
            public void onHide(boolean isCompleted) {
                if (height > 0) {
                    ll_guan.scrollBy(0, -(height + DensityUtil.dp2px(mContext, 16)));
                }

                if (isCompleted) {
                    Log.i("", "你点击了完成按钮");
                }
            }

            @Override
            public void onShow() {
                ll_guan.post(new Runnable() {
                    @Override
                    public void run() {
                        //pos[0]: X，pos[1]: Y
                        int[] pos = new int[2];
                        //获取编辑框在整个屏幕中的坐标
                        editView.getLocationOnScreen(pos);
                        //编辑框的Bottom坐标和键盘Top坐标的差
                        height = (pos[1] + editView.getHeight())
                                - (ScreenUtil.getScreenHeight(mContext) - keyboardView.getHeight());
                        if (height > 0) {
                            //编辑框和键盘之间预留出16dp的距离
                            ll_guan.scrollBy(0, height + DensityUtil.dp2px(mContext, 16));
                        }

                    }
                });
            }

            @Override
            public void onPress(int primaryCode) {

            }
        });
    }

    private void setSubView() {
        editView.setEditView(llKeyboard, keyboardView, false);
    }

    public void setWeithLesson(int weithLesson) {
        this.weithLess = weithLesson;
        SimpleRecordUtil.getInstance(mContext).setPlayCompleteListener(new PlayCompleteListener() {
            @Override
            public void playComplete() {

            }
        });
    }


    public void nextWord() {
        // TODO 数据切换，涉及到界面上文字和图片的切换
        //  practisePlayControl.resetProgressBar();
        saveData();

        currentPosition++;
        if (currentPosition < mDataList.size()) {

            updateViewData();

        } else {
           // Utils.showDialog(mContext, R.string.next_lesson_dialog_msg, lessonType, mNextListener);
            String uId = UserBean.getUId();
            String json = JSON.toJSON(chinesePraciceInfor).toString();
            UserBean.putChinesePraciceInfor(mContext,chinesePraciceInfor);
            wrongList.clear();
            for (int i = 0; i <mResultdataList.size() ; i++) {
                if(!mResultdataList.get(i).isRight()){
                    wrongList.add(mResultdataList.get(i).getRightHanzi());
                }
            }
            UserBean.putListWrongChain(mContext,wrongList);
            OkGo.<String>post(AppUrl.getAppUrl(Url.DICTATION_REPORTWRITECREATE)).tag(this).params("uid",uId)
                    .params("content",json).execute(new DialogCallback<String>() {
                @Override
                public void onSuccess(Response<String> response) {
                    ToastUtils.showShort(response.body());
                    mContext.startActivity(new Intent(mContext, ChinaReportActivity.class));
                    mContext.finish();
                }
            });

        }
    }

    private void saveData() {

        AppDataBean appDataBean = mDataList.get(currentPosition);
        chinesePraciceInfor.setTotalcount(mDataList.size());
        chinesePraciceInfor.setState(currentPosition);

        TestChinesePraciticeBean.DataBean dataBean = mResultdataList.get(currentPosition);
        dataBean.setSeleteHanzi(isFristSelete);
        dataBean.setRightHanzi(appDataBean.getTone());
        if(isFristSelete.equals(appDataBean.getTone())){
            dataBean.setRight(true);
        }else {
            dataBean.setRight(false);
        }



    }


    private void startTask(float t, final AnimationDrawable draw) {
        if (draw == null) return;
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                draw.stop();
            }
        }, (int) (t * 1000));
    }

    public void beforeWord() {
        //   practisePlayControl.resetProgressBar();
        if (currentPosition <= 0)
            return;

        currentPosition--;
        if (currentPosition < mDataList.size()) {
            updateViewData();

        } else {
            // TODO 进入下一课. 会掉到StudyActivity页面来进行View的切换
            // mNextListener.onLessonChanged(lessonType - 1);
            weithLess--;
            currentPosition = 0;
            initData();
        }
    }

    public void setListener(LessonProgressInterface listener) {
        mListener = listener;
    }

    public void setNextListener(NextLessonInterface listener) {
        mNextListener = listener;
    }

    private List<Integer> getPicName(String str) {
        picLists.clear();
        if (!str.equals("") || str.equals("null")) {
            String tones[] = str.replace("|", " ").split(" ");
            for (int i = 0; i < tones.length; i++) {
                picLists.add(getResource(tones[i]));
            }

        }
        return picLists;
    }

    public int getResource(String imageName) {
        Context ctx = mContext.getBaseContext();
        int resId = getResources().getIdentifier(imageName, "drawable", ctx.getPackageName());
        return resId;
    }


    private void checkResult(TextView view, boolean isTrue, int tone) {

        if (isTrue) {
            HsSoundUtil.play(mContext, R.raw.right);
            // TODO 设置当前选择正确的标识
            if (tone == 1) {


            } else if (tone == 2) {


            } else if (tone == 3) {


            }


            AnimatorUtil.pluseAnimator(mContext, view);
        } else {
            // TODO 设置成错误的颜色
            HsSoundUtil.play(mContext, R.raw.wrong);


            AnimatorUtil.shakeAnimator(mContext, view);

        }
    }

    public void onDestroy() {


        if (cursor != null)
            cursor.close();
    }


    private void resetFirstToneImg(int number) {


    }

    // 每个空间都添加一种动画
    long durationMillis = 1000, delayMillis = 0;
    private Animation chooseViewAnimation = null;
    private Animation.AnimationListener wordViewAnimListener = null;

    private void addAnimation() {
        if (rlContstrctionParient != null) {
            wordViewAnimListener = new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {


                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            };
            chooseViewAnimation = scaleIn(rlContstrctionParient, durationMillis, delayMillis, wordViewAnimListener);
            rlContstrctionParient.post(new Runnable() {
                @Override
                public void run() {
                    chooseViewAnimation.start();

                }
            });

        }
    }

    private Animation scaleIn(View view, long durationMillis, long delayMillis, Animation.AnimationListener l) {
        ScaleAnimation animation = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(durationMillis);
        animation.setStartOffset(delayMillis);
        view.setVisibility(View.VISIBLE);
        view.startAnimation(animation);
        animation.setAnimationListener(l);
        animation.cancel();
        return animation;
    }

    @OnClick({R.id.tv_hao, R.id.tv_hao1, R.id.tv_hao2})
    public void onViewClicked(View view) {
        keyboardViewReset();
        switch (view.getId()) {
            case R.id.tv_hao:

                checkIsRight(tvHao,tvHao.getText().toString(),1);
                if("".equals(isFristSelete)){
                    isFristSelete=tvHao.getText().toString().trim();
                }
                break;
            case R.id.tv_hao1:
                checkIsRight(tvHao1,tvHao1.getText().toString(),2);
                if("".equals(isFristSelete)){
                    isFristSelete=tvHao1.getText().toString().trim();
                }
                break;
            case R.id.tv_hao2:
                checkIsRight(tvHao2,tvHao2.getText().toString(),3);
                if("".equals(isFristSelete)){
                    isFristSelete=tvHao2.getText().toString().trim();
                }
                break;
        }
    }

    private void keyboardViewReset() {
        tvHao.setBackgroundColor(getResources().getColor(R.color.transparent));
        tvHao1.setBackgroundColor(getResources().getColor(R.color.transparent));
        tvHao2.setBackgroundColor(getResources().getColor(R.color.transparent));
        tvHao.setTextColor(getResources().getColor(R.color.black));
        tvHao1.setTextColor(getResources().getColor(R.color.black));
        tvHao2.setTextColor(getResources().getColor(R.color.black));
    }

    private void checkIsRight(TextView textView,String str,int number) {
        AppDataBean appDataBean = mDataList.get(currentPosition);
        TestChinesePraciticeBean.DataBean dataBean = mResultdataList.get(currentPosition);
        String tone = appDataBean.getTone();
        if(str.equals(tone)){
            editView.hide(true);
            textViews.get(0).setText(str);
            textViews.get(0).setTextSize(45);
            dataBean.setDoing(true);
            if(number==1){
                tvHao.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_write_con));

                tvHao.setTextColor(getResources().getColor(R.color.white));
            }else if(number==2){

                tvHao1.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_write_con));
                tvHao1.setTextColor(getResources().getColor(R.color.white));
            }else {

                tvHao2.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_write_con));
                tvHao2.setTextColor(getResources().getColor(R.color.white));
            }




            HsSoundUtil.play(mContext, R.raw.right);
            AnimatorUtil.pluseAnimator(mContext, textView);
        }else {
            dataBean.setDoing(false);
            if(number==1){
                tvHao.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_red_con));

                tvHao.setTextColor(getResources().getColor(R.color.white));
            }else if(number==2){

                tvHao1.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_red_con));
                tvHao1.setTextColor(getResources().getColor(R.color.white));
            }else {
                tvHao2.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_red_con));
                tvHao2.setTextColor(getResources().getColor(R.color.white));
            }
            HsSoundUtil.play(mContext, R.raw.wrong);
            AnimatorUtil.shakeAnimator(mContext, textView);

        }
        UserBean.putChinesePraciceInfor(mContext,chinesePraciceInfor);
    }

}
